import {Component, ViewEncapsulation} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
import {EmailValidator, EqualPasswordsValidator} from '../../theme/validators';
import {UserService} from '../../services/app.user';
import {Router}  from '@angular/router';
import {AuthenticationHelper} from "../../app.authentication";
import {BaThemeSpinner}  from '../../theme/services';
import {Constants} from '../../../app/common/app.constants';
declare let toastr:any;
declare let $:any;
declare let FB:any;

@Component({
    selector: 'register',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./register.scss'],
    templateUrl: './register.html',
})
export class Register {
    constants:Constants;
    form:FormGroup;
    submitted:boolean = false;
    registerError:string = '';
    constructor(fb:FormBuilder, private userService:UserService, private router:Router, private authentication:AuthenticationHelper, private spinner:BaThemeSpinner) {
        this.constants = new Constants();
        toastr.options = {positionClass: 'toast-top-right',};
        this.form = fb.group({
            'gender': ['', []],
            'name': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
            'email': ['', Validators.compose([Validators.required, EmailValidator.validate])],
            'passwords': fb.group({
                'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
                'repeatPassword': ['', Validators.compose([Validators.required, Validators.minLength(4)])]
            }, {validator: EqualPasswordsValidator.validate('password', 'repeatPassword')})
        });
        FB.init({
            appId: '1766419320344890',
            cookie: true,
            xfbml: true,
            version: 'v2.8'
        });
      this.form.controls['gender'].setValue('Male');
    }

    // Function for register user
    onSubmit(values) {
        this.spinner.showProgress();
        this.submitted = true;
        this.registerError = '';
        if (this.form.valid) {
            let data = {
                name: values.name,
                email: values.email,
                password: values.passwords.password,
                passwordConfirm: values.passwords.repeatPassword,
                gender: values.gender
            };
            this.userService.userSignup(data).subscribe(
                data => this.registerSucces(data),
                error => this.registerFail(error)
            );
        }
    }

    // Function for registration success
    registerSucces(result) {
        toastr.success(this.constants.USERREGISTERSUCCESSFULLY);
        this.spinner.hideProgress();
        this.authentication.setLoggedIn(result.token);
        localStorage.setItem('firstname', result.user.firstName);
        localStorage.setItem('lastname', result.user.lastName);
        this.router.navigate(['dashboard']);

    }

    // Function for registration fail
    registerFail(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);
        this.submitted = false;
        this.registerError = error.error_message;
    }

    // Function for Facebook logic
    onFacebookLoginClick() {
        FB.login(
            (response) => {
                this.statusChangeCallback(response);
            }
        );
    }

    // Function for callback facebook status change
    statusChangeCallback(resp) {
        if (resp.status === 'connected') {
            // connect here with your server for facebook login by passing access token given by facebook
            let data = {token: resp.authResponse.accessToken};
            this.userService.facebookLogin(data).subscribe(
                data => {},
                error => {}
            );
        } else if (resp.status === 'not_authorized') {
            this.resetFB();
            toastr.error(this.constants.FBERROR);
        } else {
            this.resetFB();
            toastr.error(this.constants.FBALERT);
        }
    }

    // Function for call reset Facebook
    resetFB() {
        FB.init({
            appId: '1766419320344890',
            cookie: true,
            xfbml: true,
            version: 'v2.8'
        });
    }
}
